<?php
namespace addon\cms\logic;
use app\common\logic\LogicBase;
use tpfcore\Core;
use think\Db;

class Fields extends LogicBase
{
    public function saveFields($data){
    	$validate=Core::addonValidate($this->name);
        $validate_result = $validate->scene("add")->check($data['fields']);
        if (!$validate_result) {
            return [RESULT_ERROR, $validate->getError(), null];
        }

        $customform_model = Core::loadAddonModel("CustomForm");

        $fields = $customform_model->getOneObject(["id"=>$data['id']],"table,fields");

        $data_fields['id']=$data["id"];

        $insert_fields=[];

        // 编辑
        if(empty($fields['fields'])){

            $insert_fields = $data_fields['fields'][]=$data['fields'];

        }else{
            $data_fields_old = $fields['fields'];
            
            // 编辑
            if(isset($data['fields_id']) && is_numeric($data['fields_id'])){
                $data_fields_old[$data['fields_id']]=$data['fields'];
            }else{
                /* 判断field是否已经存在,编辑情况不验证 */
                foreach ($data_fields_old as $key => $value) {
                    if($value['name'] == $data['fields']['name'] || $value['title'] == $data['fields']['title']){
                        return [RESULT_ERROR,"该字段已存在"];
                    }
                }

                $insert_fields = $data_fields_old[]=$data['fields'];

            }

            $data_fields['fields']=$data_fields_old;
        }

        /*
            字段只能添加，添加后不能再修改
        */
        $sql="";
        if($insert_fields){
            $table_name = DB_PREFIX.$fields['table'];
            $column=$insert_fields['name'];
            $type=$insert_fields['type'];
            $default = $insert_fields['exts']['default']?:'';
            $comment = $insert_fields['title']?:'';
            switch ($type) {
                case 'text':
                    $sql = "alter table $table_name add $column varchar(255) DEFAULT '$default' COMMENT '$comment';";
                    break;
                case 'textarea':
                     $sql = "alter table $table_name add $column varchar(255) DEFAULT '$default' COMMENT '$comment';";
                    break;
                case 'select_type':
                    $sql = "alter table $table_name add $column {$insert_fields['exts']['field_type']} DEFAULT '$default' COMMENT '$comment';";
                    break;
                default:
                    # code...
                    break;
            }
        }

        try {

            $sql && Db::execute($sql);

            $result=$customform_model->saveObject($data_fields);

            if($result){
                return [RESULT_SUCCESS,"操作成功",url('cms/Fields/index',['form_id'=>$data['id']])];
            }else{
                return [RESULT_ERROR,"操作失败",null];
            }

        } catch (\Exception $e) {
            return [RESULT_ERROR,"sql语句操作失败".$e->getMessage(),null];
        }
 
    }
    public function getFieldList($where=[]){
        return self::getList($where);
    }   
    public function delFields($data){

        $customform_model = Core::loadAddonModel("CustomForm");

        $list = $customform_model->getList(["where"=>["id"=>$data['form_id']]]);

        if(empty($list)){
            return [RESULT_SUCCESS,"操作失败",url('cms/CustomForm/index')];
        }

        $fields = $list[0]['fields'];

        $table_name = DB_PREFIX.$list[0]['table'];
        $column = $fields[$data['id']]['name'];

        unset($fields[$data['id']]);

        $sql ="alter table $table_name drop column $column;";

        try {

            $sql && Db::execute($sql);

            $result = $customform_model->updateObject(["id"=>$data['form_id']],["fields"=>$fields]);
        
            if($result){
                return [RESULT_SUCCESS,"操作成功",url('cms/Fields/index',["form_id"=>$data['form_id']])];
            }else{
                return [RESULT_ERROR,"操作失败",null];
            }

        } catch (\Exception $e) {
            return [RESULT_ERROR,"sql语句操作失败".$e->getMessage(),null];
        }
    }
}